import axios from 'axios';
import lodash from 'lodash';
import pathToRegexp from 'path-to-regexp';
import { Toast } from 'antd-mobile';
// import { message } from 'antd';
import config from './config';
import router from 'umi/router';

const { apiPrefix } = config;

const fetch = options => {
  let { method = 'post', headers = { 'Content-Type': 'application/json' }, url, data } = options;

  axios.defaults.headers.post['Content-Type'] = headers['Content-Type'];
  axios.defaults.withCredentials = true;

  const cloneData = lodash.cloneDeep(data);

  try {
    let domin = '';
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      domin = url.match(/[a-zA-z]+:\/\/[^/]*/)[0];
      url = url.slice(domin.length);
    }
    const match = pathToRegexp.parse(url);
    url = pathToRegexp.compile(url)(data);
    for (let item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name];
      }
    }
    url = domin + url;
  } catch (e) {
    Toast.fail(e.message, 2);
  }

  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, {
        params: cloneData,
      });
    case 'delete':
      return axios.delete(url, {
        data: cloneData,
      });
    case 'post':
      return axios.post(url, cloneData);
    case 'put':
      return axios.put(url, cloneData);
    case 'patch':
      return axios.patch(url, cloneData);
    default:
      return axios(options);
  }
};

export default function request(option, options = {}) {
  let requestOption = {};
  if (!options) {
    requestOption = {
      url: apiPrefix + (option.url || option),
    };
  } else {
    options.data = options.data || options.body;
    requestOption = {
      url: apiPrefix + option,
      ...options,
    };
  }
  // loading  如果loading 设置为 false 则不loading,反之~
  options.loading === false || window.g_app._store.dispatch({ type: 'app/doLoading' });
  return fetch(requestOption)
    .then(response => {
      // 取消 loading
      window.g_app._store.dispatch({ type: 'app/doLoaded' });
      const { statusText, status, headers } = response;
      window.serverDate = new Date(headers.date);
      // const { showMsg } = requestOption; // 是否显示message
      const data = response.data;

      // 接口瞎几把写无法适配
      //   let iscodeOk; // api返回的code
      //   if (!data) {
      //     iscodeOk = true; // 登录接口成功无返回数据，特殊处理
      //   } else {
      //     iscodeOk = Number(data.code) === 200;
      //   }
      //   // api未返回data  默认显示message；showMsg 强制决定是否显示message
      //   const showMessage = () => {
      //     iscodeOk
      //       ? message.success(data.msg || '操作成功!')
      //       : message.error(data.msg || '操作失败了!请重试');
      //   };
      //   if (showMsg === undefined) {
      //     data.data !== 0 && !data.data && showMessage();
      //   } else if (showMsg) {
      //     showMessage();
      //   }

      return {
        //   success: iscodeOk,
        message: statusText,
        statusCode: status,
        data: data || undefined,
      };
    })
    .catch(error => {
      // 取消 loading
      window.g_app._store.dispatch({ type: 'app/doLoaded' });
      const { showMsg } = requestOption; // 是否显示message
      const { response } = error;
      let msg;
      let statusCode;
      if (response && response instanceof Object) {
        const { data, statusText, headers } = response;
        window.serverDate = new Date(headers.date);
        statusCode = response.status;
        msg = data.msg || data.message || statusText || '出错了，请重试！';
        switch (msg) {
          case 'Authentication failed':
            msg = '登录失败！请确认登录账号及密码是否正确';
            break;
          case 'Access Denied':
            msg = '登录状态失效！请重新登录';
            break;
          case 'Gateway Timeout':
            msg = '请求超时，请稍后重试';
            break;
          case 'Internal Server Error':
            msg = '服务器错误！请稍后重试';
            break;
          case 'Network Error':
            msg = '网络连接失败！请稍后重试';
            break;
          case 'Not Found':
            msg = '服务器连接失败！请稍后重试';
            break;
          default:
            break;
        }
        if (statusCode === 401) {
          setTimeout(() => {
            // Toast.fail(msg, 2);
            router.push('/login');
          }, 1500);
        } else {
          showMsg && Toast.fail(msg, 2);
        }
      } else {
        statusCode = 600;
        msg = error.message || '网络连接失败！请稍后重试';
        showMsg && Toast.fail(msg, 2);
      }
      return { success: false, statusCode, message: msg };
    });
}
